<template>
  <div class="body_right bCFF mLeft16">
    <div class="body_left_header items">
      <div class="mLeft6 c33">Основные сведения</div>
    </div>
    <div class="mTop30 account">
      <div class="account_name">
        <div class="title c33">Личное прозвище</div>
        <el-input v-model="userInfo.nickname" style="" class="mTop20 account_name_input"
          placeholder="Введите вопрос, который вы хотите проконсультировать" />
      </div>
      <div class="mTop40 account_sex">
        <div class="title c33">Пол</div>
        <div class="items mTop20">
          <div class="between mRight40" @click="commentsClick(item.sex)" v-for="(item, index) in commentsList" :key="`sex-${index}`">
            <div class="items">
              <img :src="userInfo.sex == item.sex ? '/src/assets/icons/checkout.png' : '/src/assets/icons/checkout_default.png'" alt=""
                class="checkout_img">
              <div class="mLeft20 account_sex_title c99">{{ item.name }}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="account_url mTop40">
        <div class="title c33">Пол</div>
        <el-upload
          class="avatar-uploader"
          :action="`${baseURL}/newApi/pc/my/avatar`"
          :headers="uploadHeaders"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          accept="image/jpeg,image/png"
          :limit="1"
        >
          <el-avatar v-if="userInfo.avatar" size="large" :src="userInfo.avatar" class="mTop20" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </div>
      <div class="account_age mTop40">
        <div class="title c33">Возраст</div>
        <el-input-number class="mTop20" style="width: 300px;" v-model="userInfo.age" placeholder="Пожалуйста, выберите." size="large" :controls="false"></el-input-number>
      </div>
      <div class="mTop40">
        <div class="title">Населённые пункты</div>
        <div class="items c33">
          <el-select class="mTop20" v-model="city1Select" placeholder="Пожалуйста, выберите." size="large"
            style="width: 300px;">
            <el-option v-for="(item, index) in cityList" :key="`c1-${index}`" :label="item.translated_name" :value="item.id" />
          </el-select>
          <el-select class="mTop20 mLeft20" v-model="city2Select" placeholder="Пожалуйста, выберите." size="large"
            style="width: 300px;">
            <el-option v-for="(item, index) in city2List" :key="`c2-${index}`" :label="item.translated_name" :value="item.id" />
          </el-select>
        </div>
      </div>
      <div class="account_tags mTop40">
        <div class="title c33">Интересующие категории</div>
        <div class="mTop20 tags-list">
          <SelectTags :list="tagList" :iconFlag="false" textColor="#000" color="#f3f6f8" textActiveColor="#FFF" activeColor="#0070E9"></SelectTags>
        </div>
      </div>
      <div class="account_submit mTop40 cFF center" @click="onSubmit">Сохранить</div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, onMounted, watch } from 'vue'
import SelectTags from '@/components/SelectTags/SelectTags.vue';//引入的头部的主键
import useUserStore from '@/store/modules/user'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { baseURL } from '@/api/request'
import { getRussiaCityList, getCategoryList, getInterestedCategory, setInterestedCategory, uploadUserInfo, getUserInfoMy } from '@/api/api'

const userStore = useUserStore()
//假数据 接入接口后需将其替换
const userInfo = reactive({
  nickname: userStore.userInfo.nickname,
  sex: userStore.userInfo.sex,
  avatar: userStore.userInfo.avatar,
  age: userStore.userInfo.age
})

const uploadHeaders = reactive({
  Authorization: userStore.token
})

//radio列表
let commentsList = reactive([
  {
    name: 'Мужчины',
    sex: 1,
    // flag: true
  },
  {
    name: 'Женщины',
    sex: 2,
    // flag: false
  }
])

interface CityItem {
  /**
   * 主键ID
   */
  id: number

  /**
   * 层级
   */
  level: number

  /**
   * 名称
   */
  name: string

  /**
   * 译文名称
   */
  translated_name: string

  /**
   * 子级
   */
  child: CityItem[]
}

const cityArr = userStore.userInfo.city.split('|')

const city1Select = ref(cityArr[0])
const city2Select = ref(cityArr.length && cityArr[1])
// 城市列表
const cityList = ref<CityItem[]>([])
const city2List = computed(() => {
  return cityList.value.find(a => city1Select.value && a.id == parseInt(city1Select.value))?.child || []
})

interface TagItem {
  name: string,
  id: number,
  selected: boolean
}
const tagList = reactive<TagItem[]>([])

const interestedCategoryList = ref()

watch(city1Select, () => {
  city2Select.value = ''
})

onMounted(() => {
  getRussiaCityListFun()
  getCategoryListFun()
})

const getRussiaCityListFun = () => {
  getRussiaCityList({}).then((res:any) =>{
    if(res.code == 0) {
      cityList.value = res.returnData
    }
  })
}

const getCategoryListFun = () => {
  getCategoryList({
    parentCateId: 0,
    topId: 0,
    level: 0,
    status: 1,
    isGuide: 0
  }).then((res:any) => {
    if(res.code == 0) {
      tagList.push(...res.returnData.map((i: any) => {return {name: i.translated_name, id: i.id, selected: false}}))
      getInterestedCategoryFun()
    }
  })
}

const getInterestedCategoryFun = () => {
  getInterestedCategory().then((res:any) => {
    if(res.code == 0) {
      interestedCategoryList.value = res.returnData
    }
  })
}

const commentsClick = (sex: number) => {
  console.log('接收到的值:', sex);
  userInfo.sex = sex
};

// 上传头像
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  userInfo.avatar = URL.createObjectURL(uploadFile.raw!)
  if(response.code == 0) {
    userInfo.avatar = response.returnData.url
  }
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!['image/jpeg', 'image/png'].includes(rawFile.type)) {
    ElMessage.error('Аватар картинка должна быть JPG или PNG формат!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Размер аватара не может превышать 2MB!')
    return false
  }
  return true
}

/**
 * 提交
 */
const onSubmit = () => {
  setInterestedCategory(tagList.filter(i=> i.selected).map(i => i.id)).then((res: any) => {
    if(res.code == 0) {
      console.log('设置感兴趣品类成功')
    }
  })
  const data = {
    ...userInfo
  } as any
  if(city1Select.value) {
    const city1Str = cityList.value.find(i => i.id == parseInt(city1Select.value))?.translated_name
    data['city'] = city1Str || city1Select.value
  }
  if(city1Select.value && city2Select.value) {
    const city1Str = cityList.value.find(i => i.id == parseInt(city1Select.value))?.translated_name
    const city2Str = city2List.value.find(i => i.id == parseInt(city2Select.value as string))?.translated_name
    data['city'] = (city1Str || city1Select.value) + '|' + (city2Str || city2Select.value)
  }
  uploadUserInfo(data).then((res: any) => {
    if(res.code == 0) {
      userStore.getUserInfo()
      ElMessage.success('Изменения успешно сохранены!')
    } else {
      ElMessage.error('Изменения не сохранены!')
    }
  })
}
</script>

<style lang="less" scoped>
.body {
  width: 1400px;

  &_right {
    width: 1124px;
    height: 951px;
    border-radius: 16px;
    padding: 20px;

    &_header {
      font-size: 16px;
      line-height: 16px;
      border-bottom: 1px solid #EEEEEE;
      padding-bottom: 12px;
    }

    ::v-deep .el-input__inner {
      height: 48px;

    }

    .tag {
      background: #FFF6EF;
      font-size: 14px;
      font-weight: 400;
      line-height: 14px;
      padding: 8px;
    }

    .account {
      .title {
        font-size: 16px;
        font-weight: 400;
        line-height: 16px;
      }

      &_name {
        &_input {
          width: 580px;
        }

        &_input_1 {
          width: 360px;
        }

        &_input_2 {
          width: 520px;
        }

        &_input_3 {
          width: 229px;

          ::v-deep .el-input__wrapper {
            box-shadow: none;
          }
        }

        &_tip {
          width: 221px;
          font-size: 16px;
          font-weight: 400;
          line-height: 16px;
        }

        &_img {
          width: 24px;
          height: 24px;
        }
      }

      &_tip {
        font-family: PingFang SC;
        font-size: 14px;
        font-weight: 400;
        line-height: 14px;
        color: #FF2E2E;
      }

      &_next {
        width: 164px;
        height: 48px;
        border-radius: 8px;
        font-size: 16px;
        font-weight: 400;
        line-height: 16px;
        background: #0070E9;
      }

      &_sex {
        &_title {
          font-family: PingFang SC;
          font-size: 16px;
          font-weight: 400;
          line-height: 16px;
          text-underline-position: from-font;
          text-decoration-skip-ink: none;
        }
      }

      &_url {
        img {
          width: 64px;
          height: 64px;
          border-radius: 50%;
        }
      }

      &_age {
        ::v-deep .el-input-number .el-input__inner {
          text-align: left;
        }
      }

      &_tags {
        .tags-list {
          max-height: 150px;
          overflow-y: auto;
        }
      }

      &_submit {
        width: 122px;
        height: 48px;
        border-radius: 8px;
        background: #0070E9;
        font-size: 16px;
        font-weight: 400;
        line-height: 16px;
      }
    }
  }
}
</style>